package com.pgytesting.mobilecertpay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pgytesting.mobilecertpay.dao.NaCaptchaInformationDao;
import com.pgytesting.mobilecertpay.dao.NaSecretDao;
import com.pgytesting.mobilecertpay.entity.NaBusinessInformation;
import com.pgytesting.mobilecertpay.dao.NaBusinessInformationDao;
import com.pgytesting.mobilecertpay.entity.NaCaptchaInformation;
import com.pgytesting.mobilecertpay.entity.NaSecret;
import com.pgytesting.mobilecertpay.service.NaBusinessInformationService;
import com.pgytesting.mobilecertpay.util.FaceIDCread;
import com.pgytesting.mobilecertpay.util.ResponseMassage;
import com.pgytesting.mobilecertpay.util.UtilMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 商户信息表(NaBusinessInformation)表服务实现类
 *
 * @author makejava
 * @since 2019-05-10 10:22:59
 */
@Slf4j
@Service("naBusinessInformationService")
public class NaBusinessInformationServiceImpl implements NaBusinessInformationService {
    @Resource
    private NaBusinessInformationDao naBusinessInformationDao;

    @Resource
    private NaSecretDao naSecretDao;

    @Resource
    private NaCaptchaInformationDao naCaptchaInformationDao;

    private static final Long TEN_MINUTES = 600000L;


    /**
     * 通过ID查询单条数据
     *
     * @param merchantId 主键
     * @return 实例对象
     */
    @Override
    public NaBusinessInformation queryById(String merchantId) {
        return this.naBusinessInformationDao.queryById(merchantId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<NaBusinessInformation> queryAllByLimit(int offset, int limit) {
        return this.naBusinessInformationDao.queryAllByLimit(offset, limit);
    }

    /**
     * 条件查询多条数据
     *
     * @param naBusinessInformation 实例对象
     * @return 对象列表
     */
    @Override
    public List<Map<String, Object>> queryAll(NaBusinessInformation naBusinessInformation) {
        List<NaBusinessInformation> paramList = this.naBusinessInformationDao.queryAll(naBusinessInformation);
        List<Map<String, Object>> resultList = new LinkedList<>();
        for (NaBusinessInformation businessInformation : paramList) {
            Map<String, Object> resulltMap = new LinkedHashMap<>();
            resulltMap.put("merchantId", businessInformation.getMerchantId());
            resulltMap.put("appName", businessInformation.getAppName());
            resultList.add(resulltMap);
        }
        return resultList;
    }

    /**
     * 新增数据
     *
     * @param json json参数
     * @return 实例对象
     */
    @Override
    public Map<String, Object> insert(JSONObject json) {
//        log.info("进行私钥获取");
//        NaSecret naSecret = new NaSecret();
//        naSecret.setMerchantMail(String.valueOf(paraMap.get("merchantMail")));
//        naSecret = naSecretDao.queryById(naSecret);
//        String encryptionData;
//        try {
//            log.info("进行数据解密操作");
//            encryptionData = RSAUtils.getSegDecryption(naSecret.getPrivateKey(), String.valueOf(paraMap.get("data")));
//        }catch (Exception e){
//            return ResponseMassage.getResMassage("99033");
//        }
//
//        JSONObject json;
//        try {
//            log.info("进行参数转换");
//            json = JSONObject.parseObject(encryptionData);
//        }catch (Exception e){
//            return ResponseMassage.getResMassage("99012");
//        }

        log.info("获取商户数据");
        // 短信验证码
        String mailCode = String.valueOf(json.get("mailCode"));
        log.info("进行邮箱验证码验证");
        NaCaptchaInformation naCaptchaInformation = new NaCaptchaInformation();
        naCaptchaInformation.setCaptchaType("1000010");
        naCaptchaInformation.setMerchantMail(String.valueOf(json.get("merchantMail")));
        naCaptchaInformation = naCaptchaInformationDao.queryById(naCaptchaInformation);
        if (naCaptchaInformation == null) {
            return ResponseMassage.getResMassage("10001");
        }
        if (!mailCode.equals(naCaptchaInformation.getMailCode())) {
            return ResponseMassage.getResMassage("10008");
        }
        // 进行验证码有效时间验证
        if ((naCaptchaInformation.getCurrentTime() + TEN_MINUTES) < UtilMethod.unixLong()) {
            log.info("验证码过期，请重新获取");
            return ResponseMassage.getResMassage("20009");
        }
        log.info("验证码校验通过");
        /**
         * 校验短信验证码，暂未实现
         */

        NaBusinessInformation naBusinessInformation = new NaBusinessInformation();
        //商户要接入的软件名称
        naBusinessInformation.setAppName(String.valueOf(json.get("appName")));
        // 生成APP ID
        naBusinessInformation.setAppId(UtilMethod.getUniqueCode());
        // 商户代码
        naBusinessInformation.setMerchantId(UtilMethod.md5Encryption(UtilMethod.getUniqueCode()));
        // 商户手机号
        naBusinessInformation.setMobileNo(String.valueOf(json.get("mobileNo")));
        // 需要接入的密码
        naBusinessInformation.setAccessPassword(UtilMethod.md5Encryption(String.valueOf(json.get("accessPassword"))));
        // 负责人姓名
        naBusinessInformation.setPrincipalName(String.valueOf(json.get("principalName")));
        // 身份证号码
        naBusinessInformation.setIdCardNumber(String.valueOf(json.get("idCardNumber")));
        // 身份证正面
        naBusinessInformation.setIdCardFront(String.valueOf(json.get("IdCardFront")));
        // 身份证反面
        naBusinessInformation.setIdCardNegative(String.valueOf(json.get("IdCardNegative")));

//        // 前台回调地址暂不实现
//        naBusinessInformation.setFrontCallbackUrl(String.valueOf(json.get("frontCallbackUrl")));
//        // 后台通知地址,暂不实现
//        naBusinessInformation.setRearCallbackUrl(String.valueOf(json.get("rearCallbackUrl")));
//        // ip限制,暂不实现
//        naBusinessInformation.setIpRestrictions(Integer.valueOf(String.valueOf(json.get("iPRestrictions"))));

        // 商户需要绑定的银行卡号
        naBusinessInformation.setBankCardNo(String.valueOf(json.get("bankCardNo")));
        // 商户需要绑定的银行卡号归属
        naBusinessInformation.setBankName(String.valueOf(json.get("bankName")));
        // 商户绑定的邮箱账号
        naBusinessInformation.setMerchantMail(String.valueOf(json.get("merchantMail")));


        log.info("进行身份证信息验证");
        Map ideInformation = FaceIDCread.getFaceIDCread(naBusinessInformation.getIdCardFront());
        String idCardNumber = String.valueOf(ideInformation.get("id_card_number"));
        String name = String.valueOf(ideInformation.get("name"));
        if (!idCardNumber.equals(naBusinessInformation.getIdCardNumber()) && !name.equals(naBusinessInformation.getPrincipalName()))
            return ResponseMassage.getResMassage("00024");
        log.info("身份证信息验证通过，进行商户数据入库");
        try {
            naBusinessInformationDao.insert(naBusinessInformation);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseMassage.getResMassage("20003");
        }
        log.info("商户信息入库成功，进行商户ID的公钥库更新");
        NaSecret naSecret = new NaSecret();
        naSecret.setMerchantMail(naBusinessInformation.getMerchantMail());
        naSecret.setMobileNo(naBusinessInformation.getMobileNo());
        naSecret.setMerchantId(naBusinessInformation.getMerchantId());
        try {
            naSecretDao.update(naSecret);
        } catch (Exception e) {
            log.info("公钥库更新失败，进行数据商户数据回溯");
            naBusinessInformationDao.deleteById(naBusinessInformation.getMerchantId());
            return ResponseMassage.getResMassage("20003");
        }

        return ResponseMassage.getResMassage(JSONObject.toJSON(naBusinessInformation));
    }

    /**
     * 修改数据
     *
     * @param naBusinessInformation 实例对象
     * @return 实例对象
     */
    @Override
    public NaBusinessInformation update(NaBusinessInformation naBusinessInformation) {
        this.naBusinessInformationDao.update(naBusinessInformation);
        return this.queryById(naBusinessInformation.getMerchantId());
    }

    /**
     * 通过主键删除数据
     *
     * @param merchantId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String merchantId) {
        return this.naBusinessInformationDao.deleteById(merchantId) > 0;
    }
}